<template>
  <div ref="debuggerWrapperRef" class="k-debugger-wrapper">
    <a-space direction="vertical" fill>
      <!-- <a-input v-model="documentOption?.api">
        <template #prepend>
          <span :class="`k-api k-api-${documentOption?.method}`">{{ documentOption?.method.toUpperCase() }}</span>
        </template>
        <template #append>
          <a-button type="primary" :loading="loading" @click="handleSendRequest">发送</a-button>
        </template>
      </a-input> -->
      <div class="flex bg-gray-100 dark:bg-gray-600 py-2 px-4 mb-4">
        <span class="k-api border-r border-gray-300 pr-4" :class="`k-api-${documentOption?.method}`">{{ documentOption?.method.toUpperCase() }}</span>
        <span class="flex-1 pl-8 text-gray-600 dark:text-gray-200">{{ documentOption?.api }}</span>
      </div>
      <a-tabs default-active-key="2" position="top">
        <a-tab-pane key="1" title="请求头部">Content of Tab Panel 1</a-tab-pane>
        <a-tab-pane key="2" title="请求参数">
          <a-space direction="vertical" fill>
            <a-space :size="10">
              <a-radio-group v-model="rawType" default-value="1" type="button">
                <a-radio value="1">x-www-form-urlencoded</a-radio>
                <a-radio value="2">form-data</a-radio>
                <a-radio value="3">raw</a-radio>
              </a-radio-group>
              <a-select v-if="rawType === '3'" v-model="rawDefaultText" default-value="Auto" placeholder="Auto" :style="{ width: '320px' }">
                <a-option>Auto</a-option>
                <a-option>Text(text/plain)</a-option>
                <a-option>JSON(application/json)</a-option>
                <a-option>Javascript(application/Javascript)</a-option>
                <a-option>XML(application/xml)</a-option>
                <a-option>XML(text/xml)</a-option>
                <a-option>HTML(text/html)</a-option>
              </a-select>
            </a-space>
            <!-- <k-code ref="rawCodeRef" v-model:code="rawText" :language="modeDefine.mode" /> -->

            <a-tabs default-active-key="1" position="top" class="k-debugger-response">
              <template #extra>
                <a-descriptions>
                  <a-descriptions-item label="请求状态:">
                    <a-tag color="cyan">{{ responseResult.status }} {{ responseResult.statusText }}</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="耗时:">
                    <a-tag color="cyan">{{ responseResult.timeConsuming }}</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="大小:">
                    <a-tag color="cyan">{{ responseResult.size }}</a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </template>
              <a-tab-pane key="1" title="Body">
                <k-code ref="responseRef" v-model:code="responseData" language="json" class="k-response-code">
                  <template #tools>
                    <a-button type="primary" size="mini">复制</a-button>
                  </template>
                </k-code>
              </a-tab-pane>
              <a-tab-pane key="2" title="Raw">
                <!-- <a-textarea v-model="responseData" disabled /> -->
                <code>
                  <pre>
                    {{ responseData }}
                  </pre>
                </code>
              </a-tab-pane>
              <a-tab-pane key="3" title="Headers">Content of Tab Panel 1</a-tab-pane>
              <a-tab-pane key="4" title="Curl">Content of Tab Panel 1</a-tab-pane>
            </a-tabs>
          </a-space>
        </a-tab-pane>
        <a-tab-pane key="3" title="AfterScript">
          <a-space direction="vertical" fill>
            <div>
              关于AfterScript更详细的使用方法及介绍,请
              <a-link href="https://gitee.com/xiaoym/knife4j/wikis/AfterScript" target="_blank">参考文档</a-link>
              <a-button type="primary" @click="codeFormatter">格式化</a-button>
            </div>
            <k-code v-model="jsCode" language="javascript" />
          </a-space>
        </a-tab-pane>
      </a-tabs>
    </a-space>
  </div>
</template>

<script setup lang="ts">
  import { CustomHttp } from '@/http/request'
  import { formatterByteSize, formatterTime, getBlobLength } from '@/utils/tools'
  import { defaultProps, documentInjectionKey, IDocumentProps } from '@/views/document/types'
  import { js_beautify as JsFormatter } from 'js-beautify'
  import vkBeautify from 'vkbeautify'
  import { rawModeDefine } from './types'

  const knifeStore = useKnifeStore()
  const { documentOption } = storeToRefs(knifeStore)

  const debuggerWrapperRef = ref<HTMLElement | undefined>()
  const loading = ref(false)
  const documentParams = inject<IDocumentProps>(documentInjectionKey, defaultProps)
  const { api, method } = documentParams
  const responseRef = ref()
  const responseData = ref()
  interface IRequestInfoProps {
    status: number | string
    statusText: string
    size: string
    timeConsuming: string
  }
  const responseResult = reactive<IRequestInfoProps>({
    status: 0,
    statusText: '',
    size: '0 B',
    timeConsuming: '0 s'
  })
  const handleSendRequest = async () => {
    loading.value = true
    const startTime = new Date().getTime()
    CustomHttp[method](api)
      .then((response: any) => {
        const { status, statusText, request, data } = response
        const timeConsuming = new Date().getTime() - startTime
        responseResult.status = status
        responseResult.statusText = statusText
        responseResult.timeConsuming = formatterTime(timeConsuming)
        let responseSize = 0
        if (request.responseType === 'blob') {
          // blob类型
          responseSize = request.response.size
        } else {
          responseSize = getBlobLength(request.responseText)
        }
        responseResult.size = formatterByteSize(responseSize)
        responseData.value = JSON.stringify(data)
      })
      .finally(() => {
        loading.value = false
      })
  }

  // raw相关
  const rawType = ref('1')
  const rawDefaultText = ref('Javascript(application/Javascript)')
  const text = ''
  const rawText = ref(text)

  const rawCodeRef = ref()
  const modeDefine = computed(() => rawModeDefine[rawDefaultText.value])

  // AfterScript
  const jsCode = ref('')
  const codeFormatter = () => {
    jsCode.value = JsFormatter(jsCode.value)
  }
</script>

<style lang="less" scoped>
  .k-debugger-wrapper {
    height: calc(100vh - 130px);

    :deep(.arco-tabs-content) {
      padding-top: 16px;
    }

    .k-debugger-response {
      :deep(.arco-tabs-content) {
        padding-left: 0;
      }
      .k-response-code {
        position: relative;
        height: 100%;

        &-tools {
          position: absolute;
          top: 0;
          right: 10px;
          z-index: 99;
        }
      }
    }
  }
</style>
